<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li><a class="link1" href="/home">home</a></li>
        <li><a class="link2" href="/about">about</a></li>
    </ul>

    <div id="routerView"></div>

    <script>
        // 只要用pushState 或 replaceState让url变化的，就能用popstate监听到
        window.addEventListener('popstate', onPopstate)
      

        function onPopstate() {
            // console.log();
            switch (location.pathname) {
                case '/home':
                    routerView.innerHTML = '<h2> home </home>'
                    return
                case '/about':
                routerView.innerHTML = '<h2> about </home>'
                    return
                default:
                    return
            }
        }

        function onLoad () {
            var routerView = document.getElementById('routerView')
            onPopstate()

            // 拦截a标签的点击事件
            var linkList = document.querySelectorAll('ul li a')
            linkList.forEach(el => {
                el.addEventListener('click', function(e) {
                    e.preventDefault() // 阻止默认事件发生
                    console.log(e);
                    history.pushState(null, '', el.getAttribute('href'))
                    onPopstate()
                })
            })
           
        }

        window.addEventListener('DOMContentLoaded', onLoad)
    </script>
</body>
</html>